package com.cloudptt.wp.ui.message;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudptt.api.comm.CauseCont;
import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.comm.FileOperation;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.config.msg.MsgConfig;
import com.cloudptt.api.product.func.message.MsgListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.MsgOperator;
import com.cloudptt.wp.R;
import com.cloudptt.wp.ScreenManager;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.BaseActivity;
import com.cloudptt.wp.ui.message.adapter.IDownload;
import com.cloudptt.wp.ui.message.adapter.IUptUi;
import com.cloudptt.wp.ui.message.adapter.SessionAdapter;
import com.cloudptt.wp.ui.views.EditLayout;
import com.cloudptt.wp.ui.views.MulSelectedOpLayout;
import com.cloudptt.wp.ui.views.PTTLayout;
import com.cloudptt.wp.ui.views.listener.CallSysDlgListener;
import com.cloudptt.wp.ui.views.listener.CustomListener;
import com.cloudptt.wp.ui.views.listener.EditLyChangeListener;
import com.mcptt.comm.CommonFunc;
import com.mcptt.config.body.info.mcdata.FileMataInfo;
import com.mcptt.config.body.info.mcdata.McdataInfoBody;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.McIdInfo;
import com.mcptt.db.loader.msg.SessionListLoader;
import com.mcptt.db.loader.msg.SessionListLoaderCb;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.SessionInfo;
import com.mcptt.http.operator.IHttpOpCb;
import com.mcptt.http.operator.file.OnDownloadListener;
import com.mcptt.http.operator.file.OnUploadListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class SessionActivity extends BaseActivity implements MsgListener,SessionListLoaderCb, View.OnClickListener, CustomListener,EditLyChangeListener,IHttpOpCb,OnUploadListener, OnDownloadListener, IDownload, IUptUi {

	private static final String TAG = "SessionActivity";
	public static final String KEY = "session";
	//	private static final int UPLOAD = 1;
//	private static final int UPLOAD_FINISH = 2;
	private static final int PICK_FILE_REQUEST = 2;
	private static final int REQUEST_CODE_CHOOSE_PIC = 0;
	private static final int REQUEST_CODE_TAKE_PHOTO = 1;


	private AddrInfo peerAddrInfo;
	private ArrayList<SessionInfo> sessionList = null;
	private MsgOperator operator = null;
	private MsgConfig config = null;
	private ListView msgListView = null;
	private McIdInfo mcInfo = null;
	private SessionAdapter mAdapter;

	private EditLayout editLayout = null;
	private PTTLayout mPttLayout;
	private MulSelectedOpLayout mulSelectedOpLayout;

	private String curFileMetaData = "";
	private long size = 0;

	//	private String mTempPhotoPath;
	//	private Uri imageUri;
	private String localPath = null;
	private ProgressDialog dlg;


	public void onCreate(Bundle savedInstanceState){
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
		window.setStatusBarColor(getResources().getColor(R.color.gradient_end));

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_session);
		peerAddrInfo =(AddrInfo)getIntent().getSerializableExtra(KEY);
		sessionList = getIntent().getParcelableArrayListExtra(ForwardMsgActivity.KEY);
		Log.i(TAG,"onCreate peerAddrInfo =  "+ peerAddrInfo + " sessionList = " + sessionList);

		initView();
		initNotificationLayout();
		initData();

	}
	@Override
	protected void onResume() {
		initOrUpdateLoader(false);
		super.onResume();
	}

	private void initData()
	{
		Log.debug(this.getClass(), "initData ");
		SysApplication app = ((SysApplication) getApplicationContext());
		Product product = app.getProduct();
		if(product != null) {
			product.setMsgListener(this,peerAddrInfo);
			this.operator = (MsgOperator) product.getOperator(ProductConst.Func_Msg);
			this.config = product.getSysConfig().getMsgConfig();
			this.mcInfo = product.getMcpttLoginInfo().getMcIdInfo();

			if(sessionList != null
					&& sessionList.size() > 0) {
				for (Iterator<SessionInfo> itor = sessionList.iterator(); itor.hasNext(); ) {
					SessionInfo info = itor.next();
					Log.i(TAG,"onCreate info =  "+ info);
					int reqType = config.getDispositionReqType(false);
					AddrInfo senderAddrInfo = mcInfo.toAddrInfo();
					if(peerAddrInfo.isFuncType())
					{
						String curFuncNum = getCurFuncNum();
						Log.d(TAG, "procUploadSuc curFuncNum = " + curFuncNum);
						if(curFuncNum == null
								|| curFuncNum.equals(""))
						{
							CommDlg.showToast(SessionActivity.this,R.string.func_src_num_check);
							return;
						}
						String nameStr = curFuncNum;
						senderAddrInfo = new AddrInfo(AddrInfo.UserType_Func,nameStr,curFuncNum,0);
					}
					SessionInfo forwardSessionInfo = info.toForwardSessionInfo(peerAddrInfo,senderAddrInfo,reqType);
					Log.d(TAG,"sendMsgBySip forwardSessionInfo = "+ forwardSessionInfo);
					if(this.operator != null)
					{
						int result = this.operator.sendMcDataMessage(forwardSessionInfo);
						Log.d(TAG, "sendMsgBySip sendMessage result = " + result);
						if (result != CauseCont.OperateCheck_Suc) {
							String errStr = CauseCont.getOperateCheckErrStr(result, SessionActivity.this);
							CommDlg.showToast(SessionActivity.this, errStr);
						}
					}
				}
				initOrUpdateLoader(true);
			}
		}
	}

	private void initOrUpdateLoader(boolean isUpdate)
	{
		Log.v( TAG, "initOrUpdateLoader " + isUpdate);
		SysApplication app = ((SysApplication) getApplicationContext());
		Product product = app.getProduct();
		if(product != null) {
			product.setMsgListener(this,peerAddrInfo);
			this.operator = (MsgOperator) product.getOperator(ProductConst.Func_Msg);
			this.config = product.getSysConfig().getMsgConfig();
			this.mcInfo = product.getMcpttLoginInfo().getMcIdInfo();
			SessionListLoader loader = this.operator.getSessionListLoader(this, peerAddrInfo, this);
			this.operator.resetSessionCount(peerAddrInfo);
		}
	}


	private void initView()
	{


		TextView tv = (TextView) findViewById(R.id.titleTv);
		if(peerAddrInfo != null)
		{
			String name = peerAddrInfo.getDscp();
			tv.setText(name);
		}

		ImageView voiceCallIv = (ImageView) findViewById(R.id.voiceCallIv);
		voiceCallIv.setOnClickListener(this);
		if(peerAddrInfo.isGroupType())
		{
			voiceCallIv.setVisibility(View.GONE);
		}
		else
		{
			voiceCallIv.setVisibility(View.VISIBLE);
		}

		ImageView videoCallIv = (ImageView) findViewById(R.id.videoCallIv);
		videoCallIv.setOnClickListener(this);
		videoCallIv.setVisibility(View.VISIBLE);

		ImageView infoIv =  (ImageView) findViewById(R.id.infoIv);
		infoIv.setVisibility(View.VISIBLE);
		infoIv.setOnClickListener(this);


		if(peerAddrInfo != null)
		{
			String dscp = peerAddrInfo.getDscp();
			//			title.setText(dscp);
		}

		msgListView = (ListView) findViewById(R.id.msgListView);
		msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
//		msgListView.setOnItemLongClickListener(this);

//		msgListView.setOnTouchListener(new OnTouchListener() {
//			@Override
//			public boolean onTouch(View arg0, MotionEvent arg1) {
//				//imm.hideSoftInputFromWindow(contentEditText.getWindowToken(), 0);
//				//				contentEditText.clearFocus();
//				if(editLayout.isShown()){
//					editLayout.clearState();
//				}
//				if(mAdapter != null) {
//					mAdapter.clearSelect();
//				}
//				//				mExpandFuncLayout.setVisibility(View.GONE);
//				return false;
//			}
//		});

		editLayout  = (EditLayout)findViewById(R.id.bottom_edit_layout);
		editLayout.setListener(peerAddrInfo,this);

//		if(!peerAddrInfo.isGroupType()){
//		editLayout.setSwitchPTTEnable(false);
//		}

		mPttLayout  = (PTTLayout)findViewById(R.id.bottom_ptt_layout);
		mPttLayout.setCustomView(R.drawable.switch_to_editlayout, this);

		mulSelectedOpLayout  = (MulSelectedOpLayout) findViewById(R.id.mulSelectedOpLayout);
		mulSelectedOpLayout.setOpAction(this);
	}




	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}

	private void showContactDialog(final String[] arg ,final SessionInfo sInfo)
	{
		AddrInfo info = sInfo.getPeerAddrInfo();
		String name = info.getName();
		new AlertDialog.Builder(this).setTitle(name).setItems(arg,
				new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int which)
					{
						switch(which)
						{
							case 0:
								SysApplication app = ((SysApplication) getApplicationContext());
								Product product = app.getProduct();
								MsgOperator operator = (MsgOperator)product.getOperator(ProductConst.Func_Msg);
								boolean isSuc = operator.delSession(sInfo);
								Log.d(TAG, "operator.delSession isSuc = " + isSuc);
								if(isSuc)
								{
									initOrUpdateLoader(true);
								}
								break;
							case 1:
								String content  = sInfo.getContent();
								ClipboardManager cmb = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
								cmb.setText(content.trim());
								break;
						}
					}
				}).show();
	}

	//	private void showOperateDlg(final String[] arg)
	//	{
	//		new AlertDialog.Builder(this).setItems(arg,
	//				new DialogInterface.OnClickListener(){
	//			public void onClick(DialogInterface dialog, int which)
	//			{
	//				switch(which)
	//				{
	//				case 0:
	//					ClipboardManager cmb = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
	//					String content = cmb.getText().toString().trim();
	//					contentEditText.append(content);
	//					break;
	//				}
	//			}
	//		}).show();
	//	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		SessionActivity.this.setResult(RESULT_OK);
		SessionActivity.this.finish();
		operator.resetSessionCount(peerAddrInfo);
	}

	@Override
	public void onLoadFinished(List<SessionInfo> list) {
		// TODO Auto-generated method stub
		Log.d(TAG,"onLoadFinished list = " + list);
		if(mAdapter == null) {
			mAdapter = new SessionAdapter(this, peerAddrInfo, list, this, this);
			msgListView.setAdapter(mAdapter);
			msgListView.setSelection(mAdapter.getCount()-1);
		}
		else
		{
			mAdapter.refreshData(list);
			mAdapter.notifyDataSetChanged();
			msgListView.setSelection(mAdapter.getCount()-1);
		}

		//		if( null == newMessage ){
		////			contentEditText.setText( "" );
		//		}
	}

	@Override
	public void onLoaderReset() {
		// TODO Auto-generated method stub
		Log.d(TAG,"onLoaderReset");
		msgListView.setAdapter(null);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
			case R.id.infoIv:
//				this.finish();
//				overridePendingTransition( R.anim.in_from_left, R.anim.out_to_right );
				Intent intent = new Intent();
				intent.setClass(this, AddrInfoActivity.class);
				intent.getBooleanExtra(GroupMemberActivity.KEY_SHOW,false);
				intent.putExtra(SessionActivity.KEY,peerAddrInfo);
				//		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				break;
			case R.id.voiceCallIv:
				editLayout.onDoFun(R.id.voiceCallIv);
				break;
			case R.id.videoCallIv:
				editLayout.onDoFun(R.id.videoCallIv);
				break;
			default:
				break;
		}
	}

	@Override
	public void receiveMsg() {
		// TODO Auto-generated method stub
		initOrUpdateLoader(true);
	}

	@Override
	public void customFunc() {
		// TODO Auto-generated method stub
		//editLayout.showBottomLayout(EditLayout.SHOW_EDIT);
		editLayout.setVisibility(View.VISIBLE);
		mPttLayout.setVisibility(View.GONE);

	}

	@Override
	public void onSwitchPttLy() {
		// TODO Auto-generated method stub
		editLayout.setVisibility(View.GONE);
		mPttLayout.setVisibility(View.VISIBLE);
	}
	@Override
	public void onSendMsg(int contentType, String contentStr)
	{
		Log.d(TAG,"onSendMsg msgType = "+ contentType + " contentStr = "+ contentStr);
		if(peerAddrInfo == null)
		{
			CommDlg.showToast(SessionActivity.this.getApplicationContext( ), getResources().getString(R.string.please_pickup_user));
			return;
		}
		int reqType = config.getDispositionReqType(false);
		AddrInfo senderAddrInfo = mcInfo.toAddrInfo();
		if(peerAddrInfo.isFuncType())
		{
			String curFuncNum = getCurFuncNum();
			Log.d(TAG, "procUploadSuc curFuncNum = " + curFuncNum);
			if(curFuncNum == null
				|| curFuncNum.equals(""))
			{
				CommDlg.showToast(SessionActivity.this,R.string.func_src_num_check);
				return;
			}
			String nameStr = curFuncNum;
			senderAddrInfo = new AddrInfo(AddrInfo.UserType_Func,nameStr,curFuncNum,0);
		}
		SessionInfo session = new SessionInfo(peerAddrInfo, senderAddrInfo, contentType,SessionInfo.Direction_Type_Send,contentStr,reqType);
		Log.d(TAG,"sendMsgBySip MessageInfo = "+ session);
		if(this.operator != null)
		{
			int result = this.operator.sendMcDataMessage(session);
			Log.d(TAG,"sendMsgBySip sendMessage result = "+ result);
			if(result != CauseCont.OperateCheck_Suc)
			{
				String errStr = CauseCont.getOperateCheckErrStr(result,SessionActivity.this);
				CommDlg.showToast(SessionActivity.this,errStr);
			}
			else
			{
				//					contentEditText.setText("");
				initOrUpdateLoader(true);
			}
		}
	}

	@Override
	public void doAction(int subFunc) {
		// TODO Auto-generated method stub
		Log.debug(this.getClass(),"doAction subFunc = " + subFunc);
		Intent funcIntent;
		switch (subFunc) {
			case CallSysDlgListener.CHOOSE_PIC:
				funcIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				funcIntent.setType("image/*");
				startActivityForResult(funcIntent, REQUEST_CODE_CHOOSE_PIC);
				break;

			case CallSysDlgListener.OPEN_CAMERA:
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
				break;

			case CallSysDlgListener.CHOOSE_FILE:
				intent = new Intent(Intent.ACTION_GET_CONTENT);
				// 这里可以指定文件类型，例如：
				// intent.setType("image/*");  // 只选择图片
				// intent.setType("application/pdf");  // 只选择PDF文件
				// 如果想选择所有文件类型，可以使用下面的语句
				intent.setType("*/*");
				startActivityForResult(intent, PICK_FILE_REQUEST);
////				intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
////				intent.setType("*/*"); // 选择所有类型的文件
////				intent.addCategory(Intent.CATEGORY_OPENABLE);
////				startActivityForResult(Intent.createChooser(intent, "选择文件"), PICK_FILE_REQUEST);
//				intent = FileUtils.createGetContentIntent();
//				startActivityForResult(Intent.createChooser(intent, "选择文件"), PICK_FILE_REQUEST);
				break;
			case R.id.forwardMulBtn:
				if(mAdapter != null)
				{
					mAdapter.doForwardMulAction();
				}
				break;
			case R.id.deleteMulBtn:
				if(mAdapter != null)
				{
					mAdapter.doDelMulAction();
				}
				break;
			case R.id.cancelBtn:
				if(mAdapter != null)
				{
					mAdapter.cancelMulSelectedAction();
				}
				break;
			default:
				break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.v( TAG, "onActivityResult:requestCode:" + requestCode +" resultCode:" + resultCode);

		if(resultCode != RESULT_OK){
			return;
		}

		switch (requestCode) {
			case REQUEST_CODE_CHOOSE_PIC:
				if(data.getData() == null){
					return;
				}
				Uri selectedImage = data.getData();
				String[] filePathColumn = {MediaStore.Images.Media.DATA};
				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				assert cursor != null;
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				cursor.close();
				Log.debug(this.getClass(),"onActivityResult picturePath = " + picturePath);
				if(picturePath != null) {
					File file = new File(picturePath);
					curFileMetaData = FileMataInfo.toMetaData(file,0);
					size = file.length();

					showUploadDialog(true,file, size);
				}
				break;

			case REQUEST_CODE_TAKE_PHOTO:
				if (resultCode == Activity.RESULT_OK)
				{
					String sdStatus = Environment.getExternalStorageState();
					if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
						return;
					}
					Bundle bundle = data.getExtras();
					Bitmap bitmap = (Bitmap) bundle.get("data");//
					if(bitmap != null) {
						String path = FileOperation.getFilePath(SessionInfo.Filetype_Pic);
						File dir = new File(path);
						if (!dir.exists()) {
							dir.mkdirs();
						}

						//			String fileName = generateName();
						String name = generateName();
						File file = new File(dir, name);
						FileOperation.saveImgFile(file, bitmap);
						curFileMetaData = FileMataInfo.toMetaData(file,0);
						long size = file.length();
						//Toast.makeText(this, "Img fileName = " + file, Toast.LENGTH_SHORT).show();
						//				uploadFile(file);
						showUploadDialog(true,file, size);
					}
				}
				break;
			case PICK_FILE_REQUEST:
				if (resultCode == Activity.RESULT_OK)
				{
//					Intent shareIntent = new Intent(Intent.ACTION_SEND);
//					Uri fileUri = data.getData();
//					shareIntent.setType(getContentResolver().getType(fileUri));
//					shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
//					shareIntent.setPackage("com.cloudptt.wp"); // 微信包名
//					startActivity(Intent.createChooser(shareIntent, "分享文件"));
//					break;
					String sdStatus = Environment.getExternalStorageState();
					if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
						return;
					}
					Uri uri = data.getData();
					Log.debug(this.getClass(),"onActivityResult uri = " + uri);
					 try {
						 String name = getPathFromUri(uri);
						 Log.debug(this.getClass(),"onActivityResult name = " + name);
					     InputStream inputStream = getContentResolver().openInputStream(uri);

						 if(inputStream != null) {
							 String path = FileOperation.getFilePath(SessionInfo.Filetype_Pic);
							 File dir = new File(path);
							 if (!dir.exists()) {
								 dir.mkdirs();
							 }

							 File file = new File(dir, name);
							 FileOperation.saveInputStreamToFile(inputStream,file);
							 curFileMetaData = FileMataInfo.toMetaData(file,0);
							 long size = file.length();
							 //Toast.makeText(this, "Img fileName = " + file, Toast.LENGTH_SHORT).show();
							 //				uploadFile(file);
							 showUploadDialog(true,file, size);
						 }
					 } catch (FileNotFoundException e) {
					     e.printStackTrace();
					 }
//					Uri uri = data.getData();
//					Log.debug(this.getClass(),"onActivityResult uri = " + uri);
//					// 获取文件路径或文件名
//					String filePath = getPathFromUri(uri);
//					Log.debug(this.getClass(),"onActivityResult filePath = " + filePath);
//					if(filePath != null)
//					{
//						File file = new File(filePath);
//						curFileMetaData = FileMataInfo.toMetaData(file);
//						size = file.length();
//
//						showUploadDialog(file, size);
//					}
					break;
				}

			default:
				break;
		}
	}
	private String getPathFromUri(Uri uri) {
		// 获取文件路径
		String path = null;
		if (uri != null) {
			String[] proj = { DocumentsContract.Document.COLUMN_DISPLAY_NAME };
			try (Cursor cursor = getContentResolver().query(uri, proj, null, null, null)) {
				if (cursor != null && cursor.moveToFirst()) {
					int column_index = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME);
					path = cursor.getString(column_index);
				}
			}
		}
		return path;
	}

	@Override
	public void uploadVoiceMsg(long sec,String voiceMsgPath)
	{
		File file = new File(voiceMsgPath);
		String fileName = file.getName();
		curFileMetaData = FileMataInfo.toMetaData(file,sec);
		long size = file.length();
		Log.d(TAG, "audioRecorderButton onFinish size = " + size + " curFileMetaData = " + curFileMetaData);
		showUploadDialog(false,file,size);
	}

	private void uploadFile(File file,long len)
	{
		Log.d(TAG, "uploadFile file = " + file);
		if(!file.exists())
		{
			Log.d(TAG, "uploadFile file no exists pic = " + file);
			Toast.makeText(this, "file is no exist " + file, Toast.LENGTH_SHORT).show();
			if(dlg != null)
			{
				dlg.dismiss();
			}
			return;
		}
		if(operator != null)
		{
			int result = operator.checkPermission();
			if(result != CauseCont.OperateCheck_Suc)
			{
				String errStr = CauseCont.getOperateCheckErrStr(result, SessionActivity.this);
				CommDlg.showToast(SessionActivity.this, errStr);
				if(dlg != null)
				{
					dlg.dismiss();
				}
				return;
			}
		}

		SysApplication app = ((SysApplication) getApplicationContext());
		Product product = app.getProduct();
		if(product == null)
		{
			if(dlg != null)
			{
				dlg.dismiss();
			}
		}
		String peerMcdataId = peerAddrInfo.getMcxId();
		String url = product.getSysConfig().getFileSvrUrl();
		if(url != null
				&& !url.trim().equals("")) {
			if (operator == null) {
				this.operator = (MsgOperator) product.getOperator(ProductConst.Func_Msg);
			}
			String msgType = SessionInfo.MsgType_Desc_Oto_FD;
			if (peerAddrInfo.isGroupType()) {
				msgType = SessionInfo.MsgType_Desc_Group_FD;
			}
			String senderId = this.mcInfo.getAddrId();
			String clientId = this.mcInfo.getClientId();
			McdataInfoBody body = new McdataInfoBody(SessionInfo.Type_Normal,msgType, peerMcdataId, senderId, clientId);
			String infoBody = body.toString();
			int result = operator.uploadFile(url, file, len, this, this, infoBody);
			if(result != CauseCont.OperateCheck_Suc) {
				String errStr = CauseCont.getOperateCheckErrStr(result, SessionActivity.this);
				CommDlg.showToast(SessionActivity.this, errStr);
			}
		}
		else {
			CommDlg.showToast(SessionActivity.this,R.string.fd_url_null);
			if(dlg != null)
			{
				dlg.dismiss();
			}
		}

	}
	@Override
	public void onOpResult(int id,boolean isSuc,SessionInfo info,int cause,String fileUrl,File file)
	{
		Log.d(TAG, "onOpResult isSuc = " + isSuc + " fileUrl = " + fileUrl + " file = " + file);
		if(IHttpOpCb.Id_UpLoad == id) {
			if (!isSuc) {
				String result = this.getString(R.string.fail);
				Toast.makeText(this, this.getString(R.string.fd_upload) + result + fileUrl, Toast.LENGTH_SHORT).show();
			}

			if(isSuc)
			{
				procUploadSuc(fileUrl,file);
			}
			else
			{
				if(dlg != null)
				{
					dlg.dismiss();
				}
			}
		}
		else if(IHttpOpCb.Id_DownLoad == id)
		{
			Log.debug(getClass(), "onOpResult Id_DownLoad isSuc = " + isSuc);
			String result = this.getString(R.string.fail);
			if (isSuc)
			{
//				result = " successful";
				result = this.getString(R.string.success);
				SysApplication app = ((SysApplication) getApplicationContext());
				Product product = app.getProduct();
				MsgOperator operator = (MsgOperator) product.getOperator(ProductConst.Func_Msg);
				int dispositionReqType = info.getDispositionReqType();
				if((dispositionReqType & SessionInfo.DOWNLAOD) > 0) {
					operator.sendNtfMessage(info, SessionInfo.Status_FD_COMPLETED);
				}
				if(file != null) {
					info.updateLocalPath(file.toString());
					operator.updateSessionInfo(info);

					String fileMataStr = info.getFileMetaData();
					Log.debug(getClass(), "onOpResult Id_DownLoad fileMataStr = " + fileMataStr);
					FileMataInfo fileMataInfo = FileMataInfo.parse(fileMataStr);
					String type = fileMataInfo.getType();

					Log.debug(getClass(), "onOpResult Id_DownLoad type = " + type);
					if (FileOperation.isAudio(type))
					{
//						AudioPlayer.playSound(SessionActivity.this, file.toString(), null);
						if(mAdapter != null)
						{
							mAdapter.playVoiceMsg(info);
							mAdapter.notifyDataSetChanged();
						}
					}
				}
			}
			else
			{
				if(dlg != null)
				{
					dlg.dismiss();
				}
			}
			Toast.makeText(this, this.getString(R.string.fd_download) + result + localPath, Toast.LENGTH_SHORT).show();
		}
	}
	private void procUploadSuc(String fileUrl,File file)
	{
		Log.d(TAG, "procUploadSuc fileUrl = " + fileUrl + " curFileMetaData = " + curFileMetaData);
		int reqType = config.getDispositionReqType(true);
		AddrInfo senderAddrInfo = mcInfo.toAddrInfo();
		if(peerAddrInfo.isFuncType())
		{
			String curFuncNum = getCurFuncNum();
			Log.d(TAG, "procUploadSuc curFuncNum = " + curFuncNum);
			if(curFuncNum == null
					|| curFuncNum.equals(""))
			{
				CommDlg.showToast(SessionActivity.this,R.string.func_src_num_check);
				return;
			}
			String nameStr = curFuncNum;
			senderAddrInfo = new AddrInfo(AddrInfo.UserType_Func,nameStr,curFuncNum,0);
		}
		SessionInfo session = new SessionInfo(peerAddrInfo, senderAddrInfo, SessionInfo.ContentType_FileURL, SessionInfo.Direction_Type_Send, fileUrl, file.toString(),curFileMetaData,reqType);
		Log.d(TAG, "procUploadSuc session = " + session);
		if (operator != null) {
			int result = operator.sendMcDataMessage(session);
			Log.d(TAG,"procUploadSuc sendMessage result = "+ result);
			if(result != CauseCont.OperateCheck_Suc)
			{
				String errStr = CauseCont.getOperateCheckErrStr(result,SessionActivity.this);
				CommDlg.showToast(SessionActivity.this,errStr);
			}
			else
			{
				initOrUpdateLoader(true);
			}
		}
	}

	private String getCurFuncNum()
	{
		SysApplication app = ((SysApplication) getApplicationContext());
		Product product = app.getProduct();
		if(product != null)
		{
			SysConfig config = product.getSysConfig();
			return config.getCurFuncNum();
		}
		return "";
	}

//	public void onOpResult(boolean isSuc) {
//		// TODO Auto-generated method stub
//		String result = " failed";
//		if(isSuc)
//		{
//			result = " successful";
//		}
//		//Toast.makeText(this, "file upload " + result, Toast.LENGTH_SHORT).show();
//	};

	@Override
	public void onProgress(long bytesRead, long contentLength, boolean done,String remoteFilePath,long len) {
		// TODO Auto-generated method stub
		Log.debug(getClass(), "bytesRead:" + bytesRead);
		Log.debug(getClass(), "contentLength:" + contentLength);
		Log.debug(getClass(), "done:" + done);
		if(dlg == null) {
			return;
		}
		if(done)
		{
//			onSendMsg(SessionInfo.ContentType_File,remoteFilePath);
			if(dlg != null) {
				dlg.dismiss();
			}
		}
		else
		{
			float value = ((float)bytesRead)/contentLength;
			Log.debug(getClass(), "onProgress value:" + value);
			int progress = (int)(value * 100);
			Log.debug(getClass(), "onProgress progress:" + progress);
			dlg.setProgress(progress);
		}
	};

	private String generateName() {
		return CommonFunc.getDateAndTime2() + ".jpg";
	}

	public void showUploadDialog(boolean isShowDlg,File file,long len)
	{

		if(isShowDlg) {
			dlg = new ProgressDialog(SessionActivity.this);

			dlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dlg.setIcon(android.R.drawable.progress_indeterminate_horizontal);
			String str = this.getString(R.string.fd_upload);
			dlg.setMessage(str);
			dlg.setCancelable(false);
			dlg.show();
		}

		uploadFile(file,len);
	}
	@Override
	public void showDownloadDialog(SessionInfo info)
	{
		dlg = new ProgressDialog(this);

		dlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dlg.setIcon(android.R.drawable.progress_indeterminate_horizontal);
		String str = getString(R.string.fd_download);
		dlg.setMessage(str);
		dlg.setCancelable(false);
		dlg.show();

		downloadFile(info);
	}
	@Override
	public void sendNtfMessage(SessionInfo sessionInfo,byte status)
	{
		SysApplication app = ((SysApplication) getApplicationContext());
		Product product = app.getProduct();
		MsgOperator operator = (MsgOperator) product.getOperator(ProductConst.Func_Msg);
//		int dispositionReqType = sessionInfo.getDispositionReqType();
//		if((dispositionReqType & SessionInfo.DOWNLAOD) > 0) {
		operator.sendNtfMessage(sessionInfo, SessionInfo.Status_FD_COMPLETED);
//		}
	}

	private void downloadFile(SessionInfo info)
	{
		SysApplication app = ((SysApplication) getApplicationContext());
		Product product = app.getProduct();
		final String path = info.getContent();
		String fileMataStr = info.getFileMetaData();
		Log.debug(getClass(), "downloadFile path = " + path + " fileMataStr = " + fileMataStr);
		FileMataInfo fileMataInfo = FileMataInfo.parse(fileMataStr);
		String name = fileMataInfo.getFileName();
		Log.debug(getClass(), "downloadFile name = " + name);

		if (product != null) {
			MsgOperator operator = (MsgOperator) product.getOperator(ProductConst.Func_Msg);
			String localPath = FileOperation.getFilePath(SessionInfo.Filetype_File);
			if (FileOperation.isPicture(name)) {
				localPath = FileOperation.getFilePath(SessionInfo.Filetype_Pic);
			}
//						else if(Common.isAudio(name))
//						{
//							localPath = FileOperation.getFilePath(SessionInfo.Filetype_Video);
//						}

			Log.debug(getClass(), "downloadFile localPath = " + localPath);
//						File file = new File(path);
//						String name = file.getName();
			Log.debug(getClass(), "downloadFile name = " + name);
			operator.downloadFile(info,path, name, this, this);
		}
	}

	@Override
	public void onDownloading(int progress, String localPath) {
		// TODO Auto-generated method stub
		this.localPath = localPath;
		if(progress >= 100)
		{
			dlg.dismiss();
		}
		else
		{
			dlg.setProgress(progress);
		}
	}

	@Override
	public void uptUi() {
		initOrUpdateLoader(false);
	}
	@Override
	public void switchEditLayoutMulSelected()
	{
		mulSelectedOpLayout.setVisibility(View.VISIBLE);
		editLayout.setVisibility(View.GONE);
	}
	@Override
	public void switchEditLayoutEdit()
	{
		mulSelectedOpLayout.setVisibility(View.GONE);
		editLayout.setVisibility(View.VISIBLE);
	}
}
